package com.atguigu.gmall.order.api;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderDetailService;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.order.to.OrderSplitTo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.krb5.internal.AuthContext;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/order")
@RestController
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    OrderDetailService orderDetailService;

    //Post api/order/orderSplit 拆单 （库存系统调用的接口）

    /**
     * 库存系统在进行扣减是需要给我们发送拆单逻辑
     * @param orderId
     * @param wareSkuMap
     * @return 返回子订单的集合
     */
    @PostMapping("orderSplit")
    public List<OrderSplitTo> OrderSplit(@RequestParam("orderId")Long orderId,
                                         @RequestParam("wareSkuMap") String wareSkuMap) throws JsonProcessingException {
        //TODO 处理拆单
        return orderService.splitOrder(orderId,wareSkuMap);
    }

    @GetMapping("/orderInfo/details/{outTradeNo}")
    public OrderInfo getOrderInfoWithDetailsByOutTradeNo(@PathVariable("outTradeNo") String outTradeNo){
        return orderService.getOrderInfoWithDetailsByOutTradeNo(outTradeNo);
    }


    //http://api.gmall.com/api/order/auth/1/10
    @GetMapping("/auth/{pageNo}/{pageSize}")
    public Result getOrdersByPage(@PathVariable("pageNo") Integer pageNo,
                                  @PathVariable("pageSize") Integer pageSize,
                                  HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //查询当前用户的
        Page<OrderInfo> page = new Page<>(pageNo,pageSize);//分页对象
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.orderByDesc("id");

        Page<OrderInfo> infoPage = orderService.page(page, queryWrapper);
        List<OrderInfo> records = infoPage.getRecords();
        for (OrderInfo record : records) {
            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",record.getId());

            List<OrderDetail> list = orderDetailService.list(wrapper);
            record.setOrderDetailList(list);
        }
        return Result.ok(infoPage);
    }

    @GetMapping("/payed/success")
    public String changeOrderStatusPayed(@RequestParam("outTradeNo") String outTradeNo){
        orderService.changeOrderStatusPayed(outTradeNo, OrderStatus.PAID.name());
        return "ok";
    }


    @GetMapping("/getorder/{id}")
    public OrderInfo getOrderById(@PathVariable("id") Long orderId){
        return orderService.getById(orderId);
    }

  /**
     * 将前端所有订单数据全部带过来
     *
     * consignee: "" 收货人
     * consigneeTel: "" 电话
     * deliveryAddress: "" 地址
     * orderComment: "" 订单备注
     * orderDetailList: null  订单的详情
     * paymentWay: "ONLINE" 支付渠道
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestParam("tradeNo") String tradeNo,
                              @RequestBody OrderInfo orderInfo,
                              HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);

        //成功，前端直接跳转
        //1、验证令牌 tradeNo

        boolean isChecked = orderService.checkToken(userId,tradeNo);
        if (!isChecked){
            //验证失败
            return Result.build(null, ResultCodeEnum.REPEAT_SUBMIT);
        }

        //验价格，把前端提交来的订单价格和当前真的价格进行对比
        //一样，下订单，不一样，返回失败，并提示哪个商品价格有变化 TODO order_info  order_details
        //验库存，确保当前订单的商品库存是有的 ，锁库存，库存数量同时减一下，订单超时，订单取消，释放库存
        //TODO 订单场景，不存在超卖问题，解决供应链
        List<String> errMsg = orderService.checkSkuPriceAndStock(orderInfo.getOrderDetailList());
        if (!CollectionUtils.isEmpty(errMsg)){
            //验价格失败
            Result<Object> fail = Result.fail();
            //用逗号连接
            String join = String.join(",", errMsg);
            fail.setMessage(join);
            return fail;
        }


        orderInfo.setUserId(Long.parseLong(userId));//往下传递用户id
        //给数据库创建订单
        OrderInfo createOrder = orderService.createOrder(orderInfo);


        //成功,前端用js直接跳到http://payment.gmall.com/pay.html?orderId=
        //订单id怎么生成的？ TODO 我们有订单工具类，雪花算法（正常做）
        return Result.ok(createOrder.getId());
    }

    @PostMapping("/seckill/submit/order")
    public OrderInfo submitSeckillOrder(@RequestBody OrderInfo orderInfo){
        OrderInfo order = orderService.createOrder(orderInfo);

        return order;
    }
}
